package com.business.business.support.utils;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.ip.tcp.TcpOutboundGateway;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

//@EnableIntegration
//@Configuration
public class TcpClientConfig implements ApplicationListener<ApplicationEvent> {
    private final TcpGateway tcpGateway;

    //@Value("${tcp.host}")
    private String host = "127.0.0.1";

    //@Value("${tcp.port}")
    private int port = 1234;

    public TcpClientConfig(TcpGateway tcpGateway) {
        this.tcpGateway = tcpGateway;
    }


    @Bean
    public AbstractClientConnectionFactory clientCF() {
        return new TcpNetClientConnectionFactory(this.host, this.port);
    }

    @MessagingGateway(defaultRequestChannel = "clientOut")
    public interface TcpGateway {
        String send(String out);
    }

    @Bean
    public MessageChannel clientOut() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "clientOut")
    public MessageHandler tcpOutGateway(AbstractClientConnectionFactory connectionFactory) {
        TcpOutboundGateway inGate = new TcpOutboundGateway();
        inGate.setConnectionFactory(connectionFactory);
        inGate.setOutputChannelName("replyTcp");
        return inGate;
    }

    @Bean
    public MessageChannel replyTcp() {
        return new DirectChannel();
    }

    @Transformer(inputChannel = "replyTcp")        //应答默认是字节数组，需要转换，和TcpGateway.send()返回值一致
    public String convertReply(byte[] bytes) {
        return new String(bytes);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            String reply = tcpGateway.send("first");        //同步
            System.err.println("reply:" + reply);
        }
    }
}